#include "bus.h"

Bus::Bus(int contiguousBuses) :
    mContiguousBuses(contiguousBuses)
{

}

int Bus::acquireAudioBus()
{
    int currentBus = FIRST_BUS;
    bool busFound = false;

    for(int i = 0; i < audioBusList.size(); i++)
    {
        if(currentBus <= audioBusList.at(i))
        {
            currentBus += mContiguousBuses;
        }

        else
        {
            audioBusList.insert(i, currentBus);
            busFound = true;
            break;
        }
    }

    if(!busFound)
    {
        if(!audioBusList.empty())
        {
            currentBus = audioBusList.last() + mContiguousBuses;
        }

        else
        {
            currentBus = FIRST_BUS;
        }
        audioBusList.append(currentBus);
    }

    return currentBus;
}


void Bus::releaseAudioBus(int bus)
{
    audioBusList.removeAll(bus);
}


int Bus::acquireCoontrolBus()
{
    int currentBus = FIRST_BUS;
    bool busFound = false;

    for(int i = 0; i < controlBusList.size(); i++)
    {
        if(currentBus <= controlBusList.at(i))
        {
            currentBus += mContiguousBuses;
        }

        else
        {
            controlBusList.insert(i, currentBus);
            currentBus = true;
            break;
        }
    }

    if(!busFound)
    {
        currentBus = controlBusList.last() + mContiguousBuses;
        controlBusList.append(currentBus);
    }

    return currentBus;
}


void Bus::releaseControlBus(int bus)
{
    controlBusList.removeAll(bus);
}

